# app/api/v1/family/recipe.py
import logging
from typing import Optional

from fastapi import APIRouter, Body, Query, Path,Depends
from tortoise.expressions import Q

from app.controllers.family.recipe import recipe_controller
from app.schemas.family.recipe import *
from app.utils.request import RequestHandler
from app.utils.app_log import logger
from app.core.auth import get_current_user_required,get_current_superuser
from app.schemas.base.login import JWTPayload

router = APIRouter()

@router.get("/list", summary="获取食谱列表")
async def get_recipes(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: Optional[str] = Query(None, description="食谱名称，用于搜索"),
    type: Optional[str] = Query(None, description="菜系类型"),
    difficulty: Optional[int] = Query(None, description="难度等级"),
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """获取食谱列表"""
    try:
        q = Q(is_deleted=False)
        if name:
            q &= Q(name__contains=name)
        if type:
            q &= Q(type=type)
        if difficulty is not None:
            q &= Q(difficulty=difficulty)

        total, data = await recipe_controller.recipe_list(page=page, page_size=page_size, q=q)
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取食谱列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取食谱列表失败")

@router.get("/user-recipe/list", summary="获取食谱列表")
async def get_recipes(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: Optional[str] = Query(None, description="食谱名称，用于搜索"),
    type: Optional[str] = Query(None, description="菜系类型"),
    difficulty: Optional[int] = Query(None, description="难度等级"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """用户获取家庭中的食谱列表"""
    try:
        q = Q(is_deleted=False) & Q(family_id=current_user.family_id)
        if name:
            q &= Q(name__contains=name)
        if type:
            q &= Q(type=type)
        if difficulty is not None:
            q &= Q(difficulty=difficulty)

        total, data = await recipe_controller.recipe_list(page=page, page_size=page_size, q=q)
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取食谱列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取食谱列表失败")


@router.get("/{recipe_id}", summary="获取食谱详情")
async def get_recipe(
    recipe_id: int = Path(..., description="食谱ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """获取食谱详情"""
    try:
        recipe_info = await recipe_controller.get_recipe_info(recipe_id)
        return RequestHandler.success(data=recipe_info)
    except Exception as e:
        logger.error(f"获取食谱详情失败: {str(e)}")
        return RequestHandler.server_error(message="获取食谱详情失败")

@router.delete("/{recipe_id}", summary="删除食谱")
async def delete_recipe(
    recipe_id: int = Path(..., description="食谱ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """删除食谱"""
    try:
        family_id =  current_user.family_id
        delete_result = await recipe_controller.remove_recipe(recipe_id, family_id)
        if delete_result:
            return RequestHandler.success(message="食谱删除成功")
    except Exception as e:
        logger.error(f"删除食谱失败: {str(e)}")
        return RequestHandler.server_error(message="删除食谱失败")

@router.post("/create", summary="创建食谱")
async def create_recipe(
    recipe_in: RecipeCreate,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """创建食谱"""
    try:
        # logger.info(f"创建食谱: {recipe_in.name} {current_user.family_id}")
        recipe_in.user_id = current_user.user_id
        recipe_in.family_id = current_user.family_id
        recipe = await recipe_controller.create_recipe(recipe_in)
        if recipe:
            return RequestHandler.success(message="食谱创建成功", data={"id": recipe.id})
    except Exception as e:
        logger.error(f"创建食谱失败: {str(e)}")
        return RequestHandler.server_error(message="创建食谱失败")

@router.put("/{recipe_id}", summary="更新食谱")
async def update_recipe(
    recipe_id: int = Path(..., description="食谱ID"),
    recipe_in: RecipeUpdate = None,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """更新食谱"""
    try:
        if recipe_in:
            recipe_in.id = recipe_id
            family_id = current_user.family_id
        recipe = await recipe_controller.update_recipe_info(recipe_id, recipe_in, family_id)
        if recipe:
            return RequestHandler.success(message="食谱更新成功")
    except Exception as e:
        logger.error(f"更新食谱失败: {str(e)}")
        return RequestHandler.server_error(message="更新食谱失败")